#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
import ConfigParser
import PyZenity
from base import paths, config_data
from subprocess import Popen, call, PIPE
from commands import getoutput
from signal import SIGKILL

cparser = ConfigParser.RawConfigParser()

def say_bye():
    print "bye"
    
def go_deleting_config():
    os.unlink(paths.ident_file)
    os.unlink("%s.pub" % paths.ident_file)

def check_user_directory():
    if not os.path.isdir(paths.config_dir):
        create_dir = os.mkdir(paths.config_dir)
    else:
        pass

def check_config_file():
    if os.path.exists(paths.config_file):
        return True
    else:
        return False

def create_config_file():
    if PyZenity.Question("SSH-Proxify will create an identify file and register this identify\non the desired server, by this way, your ssh password will\nonly be required one time (secure way). Do you agree?"):
        os.system("ssh-keygen -N '' -f %s" % paths.ident_file)

        while True:
            user = PyZenity.GetText(text='SSH Username', entry_text='', password=False)
            if not user:
                go_deleting_config()
                say_bye()
                break
            host = PyZenity.GetText(text='SSH server to be used for tunnel?', entry_text='', password=False)
            if not host:
                go_deleting_config()
                say_bye()
                break
            port = PyZenity.GetText(text='Port for tunnel? (12347 is suggested)', entry_text='12347', password=False)
            if not port:
                go_deleting_config()
                say_bye()
                break
                
    #        os.system("ssh-copy-id -i %s %s" % paths.ident_file_pub)
            cparser.add_section(config_data.section)
            cparser.set(config_data.section, "host", host)
            cparser.set(config_data.section, "user", user)
            cparser.set(config_data.section, "port", port)
            with open(paths.config_file, 'w') as writeconfig:
                cparser.write(writeconfig)
            ssh_pass = PyZenity.GetText(text='This is the only step that your ssh password will be required, your dsa id file will be copied to server once, and because your\nmachine will be identified, your password won t be necessary anymore.\n\nSSH Password', entry_text='', password=True)

    #        sorry = pdialog().msgbox("Because there is no way better for now, you should run this command and enter\nyour ssh password once in terminal:\n\nssh-copy-id -i ~/.ssh-proxify/ident.pub %s@%s" % (user, host), 16, 100)
            copy_ident_file = Popen("ssh-copy-id -i %s.pub %s@%s" % (paths.ident_file, user, host), shell=True)
            break
    else:
        bye = say_bye()
        exit()

def read_configuration(data):
    read_it = cparser.read(paths.config_file)
    if data == "command":
        return "ssh -i %s -fND %s %s@%s" % (paths.ident_file ,cparser.get(config_data.section, "port"), cparser.get(config_data.section, "user"), cparser.get(config_data.section, "host"))
    else:
        return cparser.get(config_data.section, data)

def ask_for_tunnel():
    tunnel_action = PyZenity.List(['', 'What do you want to do?'], title='Action', boolstyle=None, editable=False, select_col=1, sep='|', data=[['1', 'Open Tunnel'], ['2', 'Edit config data']])
    if tunnel_action == None:
        return 0
    else:
        return int(tunnel_action[0])

def ask_for_x_tunnel():
    return PyZenity.Question("Tunnel is seem to be working. Do you want to close?")

def open_tunnel(host, port, user):
    call("ssh -i %s -fND %s %s@%s" % (paths.ident_file, port, user, host), shell=True)

def tunnel_init_message(check):
# This function didn't work it'll be necessary to read output.
    if check == True:
        # Looks like tunnel is successfully runned.
        tunnel_init_success = PyZenity.InfoMessage("Tunnel is successfully initialized! Now, you\ncan use %s as tunnel port." % read_configuration('port'))
    elif check == False:
        # Tunnel is not working
        tunnel_init_failure = PyZenity.InfoMessage("An error has occured. Tunnel cannot be initialized.")
    
def close_tunnel(host, port):
    os.kill(int(get_pidof_tunnel()), SIGKILL)
    tunnel_close_success = PyZenity.InfoMessage("Tunnel is closed. Connection with %s is terminated." % host)

def reedit_config():
    old_host = read_configuration("host")
    if PyZenity.Question('Your old config data will be deleted. Do you agree?'):
        user = PyZenity.GetText(text='SSH Username', entry_text=read_configuration("user"), password=False)
        host = PyZenity.GetText(text='SSH server to be used for tunnel?', entry_text=read_configuration("host"), password=False)
        port = PyZenity.GetText(text='Port for tunnel? (12347 is suggested)', entry_text=read_configuration("port"), password=False)

#        os.system("ssh-copy-id -i %s %s" % paths.ident_file_pub)
        cparser.set(config_data.section, "host", host)
        cparser.set(config_data.section, "user", user)
        cparser.set(config_data.section, "port", port)
        with open(paths.config_file, 'w') as writeconfig:
            cparser.write(writeconfig)
        if not host == old_host:
            os.unlink(paths.ident_file)
            os.unlink("%s.pub" % paths.ident_file)
            os.system("ssh-keygen -N '' -f %s" % paths.ident_file)
            ssh_pass = PyZenity.GetText(text='This is the only step that your ssh password will be required, your dsa id file will be copied to server once, and because your\nmachine will be identified, your password won t be necessary anymore.\n\nSSH Password', entry_text='', password=True)

#        sorry = pdialog().msgbox("Because there is no way better for now, you should run this command and enter\nyour ssh password once in terminal:\n\nssh-copy-id -i ~/.ssh-proxify/ident.pub %s@%s" % (user, host), 16, 100)
            copy_ident_file = Popen("ssh-copy-id -i %s.pub %s@%s" % (paths.ident_file, user, host), shell=True)

    else:
        bye = say_bye()
        exit()

def check_if_run():
    if read_configuration('command') in getoutput("ps aux| grep ssh"):
        return True
    else:
        return False

def get_pidof_tunnel():
    for line in getoutput('ps aux|grep ssh').split('\n'):
        if read_configuration('command') in line:
            return line.split()[1]
